package com.slyak.spring.jpa;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;

/**
 * sftl模板解析器，只解析后缀名为.sftl的文件
 *
 * @author stormning on 2016/12/17.
 * wangjie modified on 2019/9/17 .
 */
public class SftlNamedTemplateResolver implements NamedTemplateResolver {

    private static final Log logger = LogFactory.getLog(SftlNamedTemplateResolver.class);

    private static final String SUFFIX = ".sftl";
    
    @Override
    public Map<String, String> doInTemplateResource(Resource resource) {
        Map<String, String> sqlNamedMap = new HashMap<>();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(),
                StandardCharsets.UTF_8))) {
            String line;
            String name = null;
            StringBuilder content = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                if (isNameLine(line)) {
                    if (name != null) {
                        sqlNamedMap.put(name, content.toString());
                    }
                    name = StringUtils.trim(StringUtils.remove(line, "--"));
                    content = new StringBuilder();
                } else {
                    line = StringUtils.trimToNull(line);
                    if (line != null) {
                        content.append(line).append(" ");
                    }
                }
            }
            if (StringUtils.isNotBlank(name) && !sqlNamedMap.containsKey(name)) {
                sqlNamedMap.put(name, content.toString());
            }
        } catch (IOException e) {
            logger.error("读取模板文件" + resource.getFilename() + "出错");
        }

        return sqlNamedMap;
    }

    private boolean isNameLine(String line) {
        return StringUtils.contains(line, "--");
    }

    /* (non-Javadoc)
     * @see spring.data.jpa.repository.support.freemarker.NamedTemplateResolver#getSuffix()
     */
    @Override
    public String getSuffix() {
        return SUFFIX;
    }

}
